package belleza.relativa

import org.codehaus.groovy.grails.web.servlet.mvc.GrailsParameterMap
import belleza.relativa.security.User

class ImageService {

    def transient springSecurityService

    def agregarAFotos(GrailsParameterMap params) {

        def fotoInstance = new Foto(params)

        User user = springSecurityService.getCurrentUser() as User

        user.persona.addToFotos(fotoInstance)

        def map = ["creado": false, "foto": fotoInstance]

        map["creado"] = user.persona.save(flush: true)

        return map
    }

    def guardarFotoPrincipal(GrailsParameterMap params) {

        def principal = Foto.findByPrincipal(true);
        if (principal) {
            principal.setPrincipal(false);
            principal.save(flush: true)
        }

        def fotoInstance = new Foto(params)
        fotoInstance.setPrincipal(true)

        User user = springSecurityService.getCurrentUser() as User

        user.persona.setFotoPrincipal(fotoInstance)

        def map = ["creado": false, "foto": fotoInstance]

        map["creado"] = user.persona.save(flush: true)

        return map
    }

    def setearFotoComoPrincipal(Foto foto){
        def principal = Foto.findByPrincipal(true);
        if (principal) {
            principal.setPrincipal(false);
            principal.save(flush: true)
        }

        foto.setPrincipal(true)
        foto.save(flush: true)
    }
}
